<template>
	<section>
		<!--工具条 高级查询部分-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keywordQuery" v-perm="'department:list'">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd" v-perm="'department:save'">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表
		  :data=  ：绑定的数据   highlight-current-row 高亮
		  v-loading：转圈圈  忙等框
		  @selection-change：选中改变的时候触发
		  sortable ： 表格排序
		-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="120" sortable>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门领导" width="120" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="120" sortable>
      </el-table-column>

      <el-table-column prop="state" label="是否启用" width="100" sortable>
        <template scope="scope">
          <el-span style="color: green" v-if="scope.row.state==1" size="small" >启用</el-span>
          <el-span style="color: red" v-else-if="scope.row.state==0" size="small" >禁用</el-span>
          <el-span style="color: gray" v-else size="small">未知</el-span>
        </template>
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)" v-perm="'department:save'">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" v-perm="'department:delete'">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条：批量删除-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="totals" style="float:right;">
			</el-pagination>
		</el-col>

    <!--id: null,
    sn:'',
    name: '',
    state:1,
    manager_id: '',
    parent_id: ''-->
		<!--添加或修改的对话框-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="部门状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
        <el-form-item label="部门经理" prop="manager_id">
          <!--<el-input v-model="editForm.manager_id" auto-complete="off"></el-input>-->
          <el-select v-model="editForm.manager_id" placeholder="请选择">
            <el-option v-for="item in managers"
                       :label="item.username"
                       :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}
		            </span>
            </el-option>
          </el-select>
        </el-form-item>
				<el-form-item label="上级部门" prop="parent_id">
					<!--<el-input  placeholder="上级部门" v-model="editForm.parent_id"></el-input>-->
            <!--
             el-cascader - 级联
               :options="deptTree" - 级联框中需要的数据【集合】
             回显机制：
               v-model="saveForm.parent"
               parent：[2,5]
               'name',  级联框显示那个属性的值
               'id'    回显时需要,回传值的时候也需要
           -->
          <el-cascader v-model="editForm.parent_id"
                       :options="deptTree"
                       :props="{
            	checkStrictly: true,
                label: 'name',
                value: 'id'
            }" clearable>
          </el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="addForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="性别">
					<el-radio-group v-model="addForm.sex">
						<el-radio class="radio" :label="1">男</el-radio>
						<el-radio class="radio" :label="0">女</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="年龄">
					<el-input-number v-model="addForm.age" :min="0" :max="200"></el-input-number>
				</el-form-item>
				<el-form-item label="生日">
					<el-date-picker type="date" placeholder="选择日期" v-model="addForm.birth"></el-date-picker>
				</el-form-item>
				<el-form-item label="地址">
					<el-input type="textarea" v-model="addForm.addr"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	/*import util from '../../common/js/util'  //不需要引入外部文件，所以注释
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';*/

	export default {
		data() {
			return {
				//1.数据列表相关模型数据
				departments: [],
        listLoading: false,

        //2.分页查询数据
				totals: 0,
				currentPage: 1,
				pageSize: 5,

        //3.高级查询
        keyword:'',

        //4.批量删除
				sels: [],//列表选中列

        //5.添加或修改
        title:'',
				editFormVisible: false,//添加或修改的界面是否显示
				editLoading: false,//提交按钮上的保存模态框
				editFormRules: {  //表单项验证规则
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据，建议字符串用'',id用null
				editForm: {
					id: null,
          sn:'',
					name: '',
					state:1,
					manager_id: null,
					parent_id: null
				},
        //查询所有经理
        managers:[],

        //部门树
        deptTree: [],



				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//新增界面数据
				addForm: {
					name: '',
					sex: -1,
					age: 0,
					birth: '',
					addr: ''
				}

			}
		},
		methods: {
			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},



			//1.获取用户列表
			getDepartments() {
				let para = {
          //第一个currentPage：发送到后端的参数 ， this.currentPage:本页面的data参数
					currentPage: this.currentPage,
          pageSize:this.pageSize,
          keyword:this.keyword,
					//name: this.filters.name//暂时不用，高级查询
				};
				//开启忙等框
				this.listLoading = true;
				//发送axios需求,注意语法！，$http.post  以及  res=>{}
        this.$http.post("/department",para)
        .then(res=>{
          this.departments=res.data.data;
          this.totals=res.data.totals;
          this.listLoading = false;//关闭忙等框
        }).catch(res=>{
          this.$message.error("网络不稳定");
        })

			},
      //2.点击当前页的查询逻辑
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getDepartments();

      },
      //3.高级查询
      keywordQuery(){
        this.currentPage=1;
        this.getDepartments();
      },

			//4.删除按钮
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {//确认框
					type: 'warning'
				}).then(() => {//点击确定的时候执行
					this.listLoading = true;
					//let para = { id: row.id };
          this.$http.delete("/department/"+row.id).then(res=>{
            if(res.data.success){
              this.$message.success("删除成功");
              //处理当前页
              let totalPage = Math.ceil(this.totals/this.pageSize);//计算总页数
              //判断当前页是最后一页，且-1后整除pageSize，且不是第一页
              if(this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
                this.currentPage=this.currentPage-1;
              }

              this.getDepartments();
            }else {
              this.$message.error("网络繁忙，500")
            }
          }).catch(res=>{
            this.$message.error("网络繁忙，404，400")
          })
				}).catch(() => {
				});
			},
      //5.批量删除选项改变时触发
      selsChange: function (sels) {
			  console.log(sels);
        this.sels = sels;
      },

      //6.批量删除,向后端发送请求
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);//[1,2,3]
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //let para = { ids: ids };
          this.$http.patch("/department",ids).then(res=>{
            this.listLoading = false;
            if(res.data.success){
              this.$message.success("删除成功");//展示信息
              this.currentPage=1;//currentPage=1
              this.getDepartments();//展示第一页数据
            }else{
              this.$message.error("网络繁忙，稍后重试500");
            }
          }).catch(res=>{
            this.$message.error("网络繁忙，稍后重试500");
          })
        }).catch(() => {

        });
      },
      //7.点击新增显示对话框
      handleAdd: function () {

        this.editForm = {
          id: null,
          sn:'',
          name: '',
          state:1,
          manager_id: null,
          parent_id: null
        };
        this.title= '新增部门';
        this.getManagers();
        this.getDeptTree();
        this.editFormVisible = true;
      },

			//8.点击修改按钮显示对话框
			handleEdit: function (index, row) {
        this.title= '修改部门信息';
        this.getManagers();
        this.getDeptTree();
				this.editFormVisible = true;
				//克隆一个假的数据对象，再赋值给 editForm
				this.editForm = Object.assign({}, row);
			},

			//9.提交添加或修改的数据
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {//表单验证通过
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
						  this.editLoading = true;
							let para = Object.assign({}, this.editForm);
							let arr = para.parent_id;
              if(arr && arr.length==0){
                para.parent_id=null;
              }
							if(arr && arr.length>0){
                para.parent_id=arr[arr.length-1];
              }

							this.$http.put("/department",para).then(res=>{
                this.editLoading = false;
                this.editFormVisible = false;
                if(res.data.success){
                  this.$message.success("操作成功");//展示信息
                  //this.currentPage=1;//此处不需要重置页面
                  this.getDepartments();//展示第一页数据
                }else{
                  this.$message.error("网络繁忙，稍后重试500");
                }
              }).catch(res=>{
                this.$message.error("网络繁忙，稍后重试400");
              })
						});
					}
				});
			},
      //10.查询所有经理
      getManagers:function (){
          this.$http.get("/employee").then(res=>{
            this.managers=res.data;
          }).catch(res=>{
            this.$message.error("无法获取经理信息")
          })
      },
      //11.获取部门树 - 无限级联
      getDeptTree(){
        this.$http.get("/department/deptTree").then(res => {
          this.deptTree = res.data;
        })
      },



		},
		mounted() {
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>